package com.hxkcloud.nurse.activitys;

import android.content.Intent;
import android.os.Bundle;
import android.os.Message;
import android.support.v7.widget.LinearLayoutManager;
import android.text.Editable;
import android.text.TextWatcher;
import android.view.KeyEvent;
import android.view.View;
import android.view.inputmethod.EditorInfo;
import android.widget.AdapterView;
import android.widget.EditText;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;

import com.hyphenate.easeui.EaseConstant;
import com.hxkcloud.nurse.R;
import com.hxkcloud.nurse.adapter.HistoryRecordAdapter;
import com.hxkcloud.nurse.adapter.UserManagerAdapter;
import com.hxkcloud.nurse.beans.UserManagerBean;
import com.hxkcloud.nurse.beans.UserManagerInfo;
import com.hxkcloud.nurse.beans.resultbeans.ObjectResultBean;
import com.hxkcloud.nurse.request.MessageCode;
import com.hxkcloud.nurse.request.YiJiaHuNetWorkUtils;
import com.hxkcloud.nurse.utils.SharedPreferenceUtil;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullToRefreshLayout;
import com.hxkcloud.nurse.views.pulltorefreshlayout.PullableRecyclerView;

import java.util.ArrayList;
import java.util.LinkedList;
import java.util.List;

/**
 * Created by ray_lei on 2016/7/7.
 */
public class SearchUserManagerActivity extends BaseActivity implements View.OnClickListener, PullToRefreshLayout.OnRefreshListener, UserManagerAdapter.ResultSelectedListener {

    private LinearLayout wholeLayout;
    private EditText searchET;//搜索输入框
    private TextView cancelTV;//取消
    private TextView recordTV;//历史记录
    private ListView recordListView;//历史记录列表
    private ImageView iv_back;
    private HistoryRecordAdapter recordAdapter;

    private LinkedList<String> recordList;

    private PullToRefreshLayout refreshLayout;
    private PullableRecyclerView recycleView;
    private List<UserManagerBean> userManagerInfoList;
    private UserManagerAdapter adapter;

    private int pageIndex = 1;
    private int pageSize = 15;

    private boolean isLoadMore = false;// 是否加载更多

    private ObjectResultBean<UserManagerInfo> resultBean;

    private int totalCount = 0;

    private String keyword = "";

    @Override
    protected void updateByHandler(Message msg) {
        switch (msg.what) {
            case MessageCode.PREGNANTBMIADD_GETPATIENTFILTERNEWLIST_SUCCESS:
                dismisssLoading();
                if (msg.obj != null) {
                    resultBean = (ObjectResultBean<UserManagerInfo>) msg.obj;
                    totalCount = Integer.parseInt(resultBean.getData().getTotalCount());
                    if (resultBean.getData().getList().size() == 0) {
                        if (isLoadMore) {
                            refreshLayout
                                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        } else {
                            userManagerInfoList.clear();
                            adapter.setData(userManagerInfoList);
                            refreshLayout
                                    .refreshFinish(PullToRefreshLayout.SUCCEED);
                        }
                    } else {
                        if (isLoadMore) {

                        } else {
                            userManagerInfoList.clear();
                        }
                        userManagerInfoList.addAll(resultBean.getData().getList());
                        adapter.setData(userManagerInfoList);
                        if (isLoadMore) {
                            refreshLayout
                                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
                        } else {
                            refreshLayout
                                    .refreshFinish(PullToRefreshLayout.SUCCEED);
                        }

                    }

                }

                break;
            case MessageCode.PREGNANTBMIADD_GETPATIENTFILTERNEWLIST_FAILURE:
                dismisssLoading();
                if (msg.obj != null) {
                    toastMsg(msg.obj.toString());
                    return;
                }

                break;

        }

    }

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.actvity_searchusermanger);
        userManagerInfoList = new ArrayList<UserManagerBean>();
        recordList = new LinkedList<String>();
        if (SharedPreferenceUtil.getPatientHistoryKeywords(mContext) != null) {
            String list = SharedPreferenceUtil.getPatientHistoryKeywords(mContext);
            if (list != null && !"".equals(list)) {
                String list1 = list.substring(1, list.length() - 1);
                String[] arr = list1.split(",");
                System.out.println(arr[0]);
                int length = arr.length;
                if (length <= 10) {
                    for (int i = 0; i < length; i++) {
                        recordList.addFirst(arr[(length - 1) - i].trim());
                    }
                }

            }
        }


        initView();
        initData();
        initListener();
    }

    @Override
    protected void initView() {
        wholeLayout = (LinearLayout) findViewById(R.id.searchuser_layout_whole);
        setTitlePadding(wholeLayout);
        searchET = (EditText) findViewById(R.id.searchuser_et_search);
        cancelTV = (TextView) findViewById(R.id.searchuser_tv_cancel);
        recordTV = (TextView) findViewById(R.id.searchuser_tv_history);
        iv_back = (ImageView) findViewById(R.id.search_iv_back);
        recordListView = (ListView) findViewById(R.id.searchuser_lv_record);
        recordAdapter = new HistoryRecordAdapter(this, recordList);
        recordListView.setAdapter(recordAdapter);

        refreshLayout = (PullToRefreshLayout) findViewById(R.id.searchuser_refreshlayout);
        recycleView = (PullableRecyclerView) findViewById(R.id.searchuser_recyclerview);

        LinearLayoutManager mLayoutManager = new LinearLayoutManager(this);
        mLayoutManager.setOrientation(LinearLayoutManager.VERTICAL);
        recycleView.setLayoutManager(mLayoutManager);


        adapter = new UserManagerAdapter(this, userManagerInfoList, recycleView, this, screenWidth, loginInfo.getDepartmentId());
        recycleView.setAdapter(adapter);

    }

    @Override
    protected void initListener() {
        cancelTV.setOnClickListener(this);
        iv_back.setOnClickListener(this);
        searchET.addTextChangedListener(new TextWatcher() {
            @Override
            public void beforeTextChanged(CharSequence s, int start, int count, int after) {

            }

            @Override
            public void onTextChanged(CharSequence s, int start, int before, int count) {

            }

            @Override
            public void afterTextChanged(Editable s) {
                String key = searchET.getText().toString().trim();
                if (key==null||"".equals(key)){
                    recordTV.setVisibility(View.VISIBLE);
                    recordListView.setVisibility(View.VISIBLE);
                    refreshLayout.setVisibility(View.GONE);
                }
            }
        });
        searchET.setOnEditorActionListener(new TextView.OnEditorActionListener() {

            @Override
            public boolean onEditorAction(TextView v, int actionId,
                                          KeyEvent event) {
                // TODO Auto-generated method stub
                if (actionId == EditorInfo.IME_ACTION_GO || actionId == EditorInfo.IME_ACTION_NEXT || actionId == EditorInfo.IME_ACTION_SEND || actionId == EditorInfo.IME_ACTION_SEARCH ||
                        (event != null && event.getKeyCode() == KeyEvent.KEYCODE_ENTER)
                        || actionId == EditorInfo.IME_ACTION_DONE) {

                    String keywords = searchET.getText().toString().trim();

                    if (keywords == null || "".equals(keywords)) {
                        toastMsg(getResources().getString(R.string.pleaseinputcontent));
                        // 提示为空
                    } else {
                        keyword = keywords;
                        if (recordList.size() == 10) {
                            recordList.remove(recordList.size() - 1);
                        }
//                        recordList.addFirst(keywords);
                        if (recordList.contains(keyword)) {
                            System.out.println("有=========");
                        } else {
                            recordList.addFirst(keyword);
                        }

                        SharedPreferenceUtil.setPatientHistoryKeywords(mContext, recordList);
                        recordAdapter.notifyDataSetChanged();
                        recordTV.setVisibility(View.GONE);
                        recordListView.setVisibility(View.GONE);
                        refreshLayout.setVisibility(View.VISIBLE);
                        YiJiaHuNetWorkUtils.getPatientFilterResultList(null, "1", keyword, pageIndex, pageSize, handler);
                    }
                    return false;
                }
                return false;
            }
        });

        recordListView.setOnItemClickListener(new AdapterView.OnItemClickListener() {
            @Override
            public void onItemClick(AdapterView<?> parent, View view, int position, long id) {
                keyword = recordList.get(position);
                searchET.setText(recordList.get(position));
                recordTV.setVisibility(View.GONE);
                recordListView.setVisibility(View.GONE);
                refreshLayout.setVisibility(View.VISIBLE);
                YiJiaHuNetWorkUtils.getPatientFilterResultList(null, "1", keyword, pageIndex, pageSize, handler);
            }
        });
    }

    @Override
    protected void initData() {

    }

    @Override
    public void onClick(View v) {

        switch (v.getId()) {
            case R.id.search_iv_back:
                recordAdapter.notifyDataSetChanged();
                finish();
                break;
            case R.id.searchuser_tv_cancel:
//                finish();
                String keywords = searchET.getText().toString().trim();

                if (keywords == null || "".equals(keywords)) {
                    toastMsg(getResources().getString(R.string.pleaseinputcontent));
                    // 提示为空
                } else {
                    keyword = keywords;
                    if (recordList.size() == 10) {
                        recordList.remove(recordList.size() - 1);
                    }
//                        recordList.addFirst(keywords);
                    if (recordList.contains(keyword)) {
                        System.out.println("有=========");
                    } else {
                        recordList.addFirst(keyword);
                    }

                    SharedPreferenceUtil.setPatientHistoryKeywords(mContext, recordList);
                    recordAdapter.notifyDataSetChanged();
                    recordTV.setVisibility(View.GONE);
                    recordListView.setVisibility(View.GONE);
                    refreshLayout.setVisibility(View.VISIBLE);
                    YiJiaHuNetWorkUtils.getPatientFilterResultList(null, "1", keyword, pageIndex, pageSize, handler);
                }
                break;

        }
    }


    @Override
    public void onSelected(String type, UserManagerBean info) {
        if ("monitor".equals(type)) {
            Intent intent = new Intent(mContext, MonitorChart1Activity.class);
            intent.putExtra("patientId", info.getPatientId());
            startActivity(intent);
        }
        if ("remind".equals(type)) {
//            Intent intent = new Intent(mContext, NoticeActivity.class);
//            intent.putExtra("patientId", info.getPatientId());
//            startActivity(intent);
            Intent intent = new Intent(mContext, PatientBetterPlanActivity.class);
            intent.putExtra("patientId", info.getPatientId());
            startActivity(intent);
        } else if ("chat".equals(type)) {
            Intent intent = new Intent(mContext, ChatFragmentActivity.class)
                    .putExtra(EaseConstant.EXTRA_USER_ID, "ejh" + info.getTel()).putExtra("name", info.getName());
            startActivity(intent);
        }
        if ("item".equals(type)) {
            Intent intent = new Intent(mContext, PatientInfoActivity.class);
            intent.putExtra("patientId", info.getPatientId());
            startActivity(intent);
        }
    }

    @Override
    public void onRefresh(PullToRefreshLayout pullToRefreshLayout) {
        isLoadMore = false;
        pageIndex = 1;
        userManagerInfoList.clear();
        YiJiaHuNetWorkUtils.getPatientFilterResultList(null, "1", keyword, pageIndex, pageSize, handler);
    }

    @Override
    public void onLoadMore(PullToRefreshLayout pullToRefreshLayout) {

        if (userManagerInfoList.size() == totalCount) {
            isLoadMore = false;
            refreshLayout
                    .loadmoreFinish(PullToRefreshLayout.SUCCEED);
            return;
        }

        isLoadMore = true;
        pageIndex++;
        YiJiaHuNetWorkUtils.getPatientFilterResultList(null, "1", keyword, pageIndex, pageSize, handler);

    }
}
